<template>
    <el-row class="login-page">
        <el-col :span="12" class="bg"></el-col>
        <el-col :span="6" :offset="3" class="form">
            <!-- 用户守则弹窗组件 -->
            <UserAgreementDialog 
                :visible="isUserAgreementVisible"
                @close="isUserAgreementVisible = false"
            />
            <!-- 注册表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
                <el-form-item>
                    <h1>注册</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                     v-model="registerData.password"></el-input>
                </el-form-item>
                <el-form-item prop="rePassword">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
                     v-model="registerData.rePassword"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-checkbox v-model="registerAgree">
                        我已阅读并同意
                        <a @click.prevent="showUserAgreement" style="color: #1890ff; cursor: pointer;">
                        用户守则
                        </a>
                    </el-checkbox>
                </el-form-item>
                <!-- 注册按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" :disabled="!registerAgree" auto-insert-space @click="register">
                        注册
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = false;">
                        ← 返回登录
                    </el-link>
                </el-form-item>
            </el-form>
            <!-- 登录表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-else :model="registerData" :rules="rules">
                <el-form-item>
                    <h1>登录</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                        <el-link type="primary" :underline="false">忘记密码？</el-link>
                    </div>
                    <div>
                        <el-checkbox v-model="loginAgree">
                            我已阅读并同意
                            <a @click.prevent.stop="showUserAgreement" style="color: #1890ff; cursor: pointer;">
                                用户守则
                            </a>
                        </el-checkbox>
                    </div>
                </el-form-item>
                <!-- 登录按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" :disabled="!loginAgree" auto-insert-space @click="login_button">登录</el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterData()">
                        没有账号？前往注册 →
                    </el-link>
                </el-form-item>
            </el-form>
        </el-col>     
    </el-row>
</template>
<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import {User, Lock} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ref, reactive, computed, toRaw  } from 'vue'
//import { userAuthentication, userLoginService } from '@/api'
import UserAgreementDialog from './userAgree.vue' // 确保路径正确
const isRegister = ref(false);

//定义数据模型
const registerData = ref({
    username: '',
    password: '',
    rePassword: ''
})
// 切换表单（0登录 1注册）
const formType = ref(0)
const loginAgree = ref(false);
const registerAgree = ref(false);

// 表单校验规则（集成式写法）
const rules = reactive({
    username: [
        { 
            required: true, 
            message: '请输入账号', 
            trigger: 'blur' 
        },
        // 手机号格式校验
        { 
            validator: (rule, value, callback) => {
                const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
                if (!phoneReg.test(value)) {
                    callback(new Error('手机号格式错误，请检查11位数字格式'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    password: [
        { 
            required: true, 
            message: '请输入密码', 
            trigger: 'blur' 
        },
        // 密码格式校验
        { 
            validator: (rule, value, callback) => {
                const reg = /^[a-zA-Z0-9_-]{4,16}$/
                if (!reg.test(value)) {
                    callback(new Error('需4-16位字母/数字/下划线/减号组合'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    rePassword: [
        { 
            required: true, 
            message: '请再次输入密码', 
            trigger: 'blur' 
        },
        // 密码一致性校验
        { 
            validator: (rule, value, callback) => {
                if (value !== registerData.value.password) {
                    callback(new Error('两次输入的密码不一致，请重新输入'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
})

//调用后台接口,完成注册
import { userRegisterService, userLoginService} from '@/api/user.js'
const register = async () => {
    let result = await userRegisterService(registerData.value);
    ElMessage({
    message: "注册成功",
    type: 'success',
  })
}
const router = useRouter()
const loginFormRef = ref()
const store = useStore()
const routerList = computed(() => store.state.menu.routerList)
const rememberMe = ref(false)
const login_button = async () => {
    try {
        // 用括号把 `await` 包裹起来
        let result = (await userLoginService(registerData.value))
        //.log("result",result)
        //console.log("registerData",registerData.value.)
        if(result.data.code === 0){
            ElMessage({
                message: "登录成功",
                type: 'success'
            })
            console.log(result,"result")
            console.log("registerData",registerData.value)
            // 保存 token 和用户信息
            localStorage.setItem('min_token', result.data.data)
            // 保存到 localStorage
            localStorage.setItem('min_userName', registerData.value.username);
            // 登录成功后跳转到首页
            router.push('/vppz/boat')
        }
        else{
            ElMessage({
                message: "登录失败，请检查账号密码",
                type: 'error'
            })
        }

    } catch (error) {
        
        console.error("登录请求出错:", error)
    }
}
//定义函数,清空数据模型的数据
const clearRegisterData = ()=>{
    registerData.value={
        username:'',
        password:'',
        rePassword:''
    }
}
// 控制用户守则弹窗的状态
const isUserAgreementVisible = ref(false);
const showUserAgreement = () => {
  isUserAgreementVisible.value = true;
};

</script>
<style lang="scss" scoped>
/* 样式 */
.login-page {
    height: 100vh;
    background-color: #fff;

    .bg {
        background: url('@/assets/image.png') no-repeat 45% 40% / 380px auto,
            url('@/assets/login_bg.jpg') no-repeat center / cover;
        border-radius: 0 20px 20px 0;
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .header {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
    
    
}
</style>